package com.hnust.controller.subject;

import com.hnust.controller.MainController;
import com.hnust.controller.subject.dialog.ModifySubjectController;
import com.hnust.domain.*;
import com.hnust.fx.AbstractFxmlView;
import com.hnust.fx.FXMLController;
import com.hnust.service.SubjectService;
import com.hnust.service.SubjectServices;
import com.hnust.store.DataStore;
import com.hnust.store.SubjectStore;
import com.hnust.view.subject.AddSubjectView;
import com.hnust.view.subject.dialog.CheckSubjectView;
import com.hnust.view.subject.dialog.ModifySubjectView;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.web.WebView;
import javafx.util.StringConverter;
import org.springframework.beans.factory.annotation.Autowired;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;


@FXMLController
public class SubjectListController implements Initializable {

    public Label dataCount;
    public Label dataRows;
    public Label dataPages;
    public TableColumn subject_num;
    @FXML
    private Pagination page;
    private final Integer rows=10;

    @FXML
    private TextField keyword;
    @FXML
    private TableColumn<SubjectTest,String> content_column;
    @FXML
    private TableColumn<SubjectTest,String> resolve_column;
    @FXML
    private TableColumn<SubjectTest,String> answer_column;

    ObservableList<SubjectTest> list;

    @FXML
    private TableColumn<SubjectTest,String> operation_column;

    @FXML
    private AnchorPane subjectListWindow;
    @FXML
    TableView<SubjectTest> tableSize;

    @FXML
    private ComboBox<CourseData> comb;
    @Autowired
    private MainController mainController;
    @Autowired
    private AddSubjectView addSubjectView;
    @Autowired
    private CheckSubjectView checkSubjectView;
    @Autowired
    private ModifySubjectView modifySubjectView;
    @Autowired
    private SubjectStore subjectStore;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private SubjectServices subjectServices;
    @Autowired
    private DataStore dataStore;
    @Autowired
    private AddSubjectController addSubjectController;
    @Autowired
    private ModifySubjectController modifySubjectController;
    ObservableList<CourseData> com;

    private String selectedCourseId;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        subjectListWindow.parentProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){
                getAllCourses();
            }else{
                comb.setItems(null);
                resetTable();
            }
        });
        //自定义操作单元格
        operation_column.setCellFactory(param -> new TableCell<SubjectTest,String>(){
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if(!empty&&item!=null){
                    HBox hBox=new HBox();
                    hBox.setAlignment(Pos.CENTER);
                    hBox.setSpacing(10);
                    Hyperlink h1=new Hyperlink("详情");
                    //增加详情弹窗
                    h1.setOnAction(event -> {
                        for(SubjectTest s:list){
                            if(s.getId().equals(item)){
                                subjectStore.setCheckSubject(s);
                                judgeDialogBtnClick(genDialog(checkSubjectView),"详情");
                                break;
                            }
                        }
                    });
                    Hyperlink h2=new Hyperlink("删除");
                    h2.setOnAction(event -> {
                        subjectService.delCourseSub(new Callback<Result>() {
                            @Override
                            public void onResponse(Call<Result> call, Response<Result> response) {
                                Platform.runLater(() -> {
                                    assert response.body() != null;
                                    if(response.body().getCode()==1){
                                        InitTable(page.getCurrentPageIndex(),rows,null);
                                        Alert alert = new Alert(Alert.AlertType.INFORMATION, "删除成功");
                                        alert.showAndWait();
                                    }else{
                                        Alert alert = new Alert(Alert.AlertType.INFORMATION, "删除失败");
                                        alert.showAndWait();
                                    }
                                });
                            }
                            @Override
                            public void onFailure(Call<Result> call, Throwable throwable) {
                                Platform.runLater(() -> {
                                    Alert alert = new Alert(Alert.AlertType.ERROR, "网络错误，请稍后再试");
                                    alert.showAndWait();
                                });
                            }
                        },item,dataStore.getTeacher_id(),dataStore.getToken());
                    });
                    h1.getStyleClass().add("color");
                    Hyperlink h3=new Hyperlink("修改");
                    h3.setOnAction(event -> {
                        //增加修改弹窗
                        for(SubjectTest s:list){
                            if(s.getId().equals(item)){
                                subjectStore.setModifySubject(s);
                                judgeDialogBtnClick(genDialog(modifySubjectView),"修改");
                                break;
                            }
                        }
                    });

                    hBox.getChildren().addAll(h1,h2,h3);
                    this.setGraphic(hBox);
                }
            }
        });
        webViewResolve(content_column);
        webViewResolve(resolve_column);
        webViewResolve(answer_column);

        comb.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){
                //System.out.println(newValue);
                selectedCourseId=newValue.getId();
                InitTable(0,rows,null);
            }
        });
        comb.setConverter(new StringConverter<CourseData>() {
            @Override
            public String toString(CourseData object) {
                return object.getName();
            }
            @Override
            public CourseData fromString(String string) {
                return null;
            }
        });
        page.currentPageIndexProperty().addListener((observable, oldValue, newValue) -> {
            InitTable(newValue.intValue(),rows,keyword.getText());
        });
    }

    private void InitTable(Integer icurrentPage,Integer irows,String ikeyword) {
        subjectService.getCourseSub(new Callback<Result<List<SubjectTest>>>() {
            @Override
            public void onResponse(Call<Result<List<SubjectTest>>> call, Response<Result<List<SubjectTest>>> response) {
                Platform.runLater(() -> {
                    if (response.body()!=null&&response.body().getData() != null){
                        if(response.body().getData().size()!=0&&response.body().getCode() == 1){
                            list = FXCollections.observableList(response.body().getData());
                            int num=1;
                            for (SubjectTest subjectTest : list) {
                                StringBuilder answers = new StringBuilder();
                                if (subjectTest.getAnswer() != null) {
                                    for (AnswerTestObj a : subjectTest.getAnswer()) {
                                        String str = "正确答案：";
                                        if (!a.getRight()) {
                                            str = "错误答案：";
                                        }
                                        answers.append(str).append(a.getContent()).append("<br/>");
                                    }
                                    subjectTest.setAnswers(answers.toString());
                                }
                                subjectTest.setNum(num++);
                            }
                            //end
                            tableSize.setItems(list);
                            int len=list.get(0).getTotal();
                            int a=len/rows;
                            if(len%rows!=0){
                                a++;
                            }
                            page.setPageCount(a);
                            dataCount.setText("共有"+len+"条数据");
                            dataPages.setText("共"+a+"页");
                        }else{
                            resetTable();
                        }
                    }else{
                       resetTable();
                    }
                });
            }
            @Override
            public void onFailure(Call<Result<List<SubjectTest>>> call, Throwable throwable) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                    alert.showAndWait();
                });
            }
        },selectedCourseId,dataStore.getTeacher_id(),dataStore.getToken(),icurrentPage,irows,ikeyword);
    }

    public void getAllCourses() {
        subjectService.getCourseData(new Callback<Result<List<CourseData>>>() {
            @Override
            public void onResponse(Call<Result<List<CourseData>>> call, Response<Result<List<CourseData>>> response) {
                Platform.runLater(() -> {
                    assert response.body() != null;
                    if(response.body().getCode()==1&&response.body().getData().size()!=0&&response.body().getData()!=null){
                        com  = FXCollections.observableArrayList(response.body().getData());
                        comb.setItems(com);
                        comb.getSelectionModel().select(0);
                    }
//                    else{
//                        Platform.runLater(() -> {
//                            Alert alert = new Alert(Alert.AlertType.INFORMATION, "没有课程数据");
//                            alert.showAndWait();
//                        });
//                    }
                });
            }

            @Override
            public void onFailure(Call<Result<List<CourseData>>> call, Throwable throwable) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                    alert.showAndWait();
                });
            }
        },dataStore.getTeacher_id(),dataStore.getToken());
    }

    @SuppressWarnings("all")
    private Dialog genDialog(AbstractFxmlView view){
        Dialog dialog=new Dialog();
        DialogPane dialogPane=new DialogPane();
        dialogPane.setStyle("-fx-background-color: #FFFFFF");
        dialogPane.setContent(view.getView());
        dialog.setDialogPane(dialogPane);
        return dialog;
    }

    private void judgeDialogBtnClick(Dialog dialog,String s){
        dialog.setGraphic(null);
        ButtonType ok=new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
        ButtonType cancel=new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE);
        dialog.getDialogPane().getButtonTypes().addAll(ok,cancel);
        Optional result=dialog.showAndWait();
        if(s.equals("详情")){
//            if(result.get()==ok){
//
//
//                //addKind(windowPaperController.getKind());
//            }else{
//
//            }
            dialog.getDialogPane().setContent(null);
        }else if(s.equals("添加")){
            if(result.get()==ok){
                addSubjectController.setAddSubject();
                List<SubjectDataInfo> subjectDataInfos = new ArrayList<>();
                subjectDataInfos.add(subjectStore.getAddSubject());
                SubjectDataListReq subjectDataListReq = new SubjectDataListReq();
                subjectDataListReq.setSubjectDataList(subjectDataInfos);
                subjectDataListReq.setToken(dataStore.getToken());
                subjectDataListReq.setId(dataStore.getTeacher_id());
                if(subjectStore.getAddSubject().getCourse_id()==null||subjectStore.getAddSubject().getChapter_id()==null
                ||subjectStore.getAddSubject().getType_id()==null||subjectStore.getAddSubject().getContent()==null
                        ||subjectStore.getAddSubject().getDifficult()==null||subjectStore.getAddSubject().getResolve()==null||
                subjectStore.getAddSubject().getKnowledgePointer()==null){
                    new Alert(Alert.AlertType.INFORMATION, "还有题目信息没有选择！").showAndWait();
                }else{
                    subjectService.addSub(new Callback<Result>() {
                        @Override
                        public void onResponse(Call<Result> call, Response<Result> response) {
                            Platform.runLater(() -> {
                                assert response.body() != null;
                                Alert alert;
                                if(response.body().getCode()==1){
                                    alert = new Alert(Alert.AlertType.INFORMATION, "添加成功！");
                                    InitTable(0,rows,null);
                                }else{
                                    alert = new Alert(Alert.AlertType.INFORMATION, "添加失败！");
                                }
                                alert.showAndWait();
                            });
                        }
                        @Override
                        public void onFailure(Call<Result> call, Throwable throwable) {
                            Platform.runLater(() -> {
                                Alert alert = new Alert(Alert.AlertType.INFORMATION, "添加失败！");
                                alert.showAndWait();
                            });
                        }
                    },subjectDataListReq);
                }
            }
            dialog.getDialogPane().setContent(null);
        }else{
            if(result.get()==ok){
                modifySubjectController.setModifySubject();
                SubjectDataInfo subjectDataInfo=subjectStore.getModifySubjectDataInfo();
                SubjectDataReq subjectDataReq=new SubjectDataReq(
                        subjectDataInfo,dataStore.getToken(),dataStore.getTeacher_id()
                );

                subjectService.updateSubInfo(new Callback<Result<String>>() {
                    @Override
                    public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                        Platform.runLater(() -> {
                            assert response.body() != null;
                            Alert alert;
                            if(response.body().getCode()==1){
                                alert = new Alert(Alert.AlertType.INFORMATION, "修改成功！");
                                InitTable(0,rows,null);
                            }else{
                                alert = new Alert(Alert.AlertType.INFORMATION, "修改失败");
                            }
                            alert.showAndWait();
                        });
                    }
                    @Override
                    public void onFailure(Call<Result<String>> call, Throwable throwable) {
                        Platform.runLater(() -> {
                            Alert alert = new Alert(Alert.AlertType.INFORMATION, "网络错误，请稍后再试");
                            alert.showAndWait();
                        });
                    }
                },subjectDataReq);
            }
        }
    }

    private void webViewResolve(TableColumn<SubjectTest,String> tableColumn){
        tableColumn.setCellFactory(param -> new TableCell<SubjectTest,String>(){
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if(item!=null&&!empty){
                    WebView webView=new WebView();
                    webView.getEngine().loadContent(item);
                    ScrollPane scrollPane=new ScrollPane();
                    scrollPane.setContent(webView);
                    scrollPane.setPrefHeight(100);
                    scrollPane.setFitToWidth(true);
                    scrollPane.setFitToHeight(true);
                    scrollPane.prefWidthProperty().bind(this.getTableColumn().widthProperty());
                    this.setGraphic(scrollPane);
                }
            }
        });
    }

    public void shiftToBatchImport(ActionEvent actionEvent) {
        mainController.skipView("批量导入");
    }

    public void addCourseSubject(ActionEvent actionEvent) throws IOException {
        subjectService.getCourseData(new Callback<Result<List<CourseData>>>() {
            @Override
            public void onResponse(Call<Result<List<CourseData>>> call, Response<Result<List<CourseData>>> response) {
                Result<List<CourseData>> result=response.body();
                assert result!=null;
                Platform.runLater(() -> {
                    if(result.getCode()==1&&result.getData().size()>0){
                        //有加入课程组才弹出添加题目弹窗
                        judgeDialogBtnClick(genDialog(addSubjectView),"添加");
                    }else{
                        Platform.runLater(() -> {
                            Alert alert = new Alert(Alert.AlertType.INFORMATION, "你还没加入任何课程组，请先加入课程组");
                            alert.showAndWait();
                        });
                    }
                });
            }
            @Override
            public void onFailure(Call<Result<List<CourseData>>> call, Throwable throwable) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                    alert.showAndWait();
                });
            }
        },dataStore.getTeacher_id(),dataStore.getToken());

    }

    public void keyWordSearch(ActionEvent actionEvent) {
        InitTable(0,rows,keyword.getText());
    }

    public void reset(ActionEvent actionEvent) {
        keyword.setText(null);
        System.out.println(tableSize.getItems());
    }

    public void resetTable(){
        page.setPageCount(1);
        tableSize.setItems(null);
        dataCount.setText("共有0条数据");
        dataPages.setText("共0页");
    }
}
